package cn.iocoder.yudao.module.alipay.service.babyorder;

import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateTime;
import cn.iocoder.yudao.module.alipay.controller.admin.infoauthaliapp.vo.InfoAuthAliAppExportReqVO;
import cn.iocoder.yudao.module.alipay.controller.app.babyorder.vo.BabyOrderCreateReqVO;
import cn.iocoder.yudao.module.alipay.controller.app.babyorder.vo.BabyOrderExportReqVO;
import cn.iocoder.yudao.module.alipay.controller.app.babyorder.vo.BabyOrderPageReqVO;
import cn.iocoder.yudao.module.alipay.controller.app.babyorder.vo.BabyOrderUpdateReqVO;
import cn.iocoder.yudao.module.alipay.dal.dataobject.infoauthaliapp.InfoAuthAliAppDO;
import cn.iocoder.yudao.module.alipay.dal.dataobject.payrecord.PayRecordDO;
import cn.iocoder.yudao.module.alipay.dal.mysql.infoauthaliapp.InfoAuthAliAppMapper;
import cn.iocoder.yudao.module.alipay.dal.mysql.payrecord.PayRecordMapper;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.alipay.controller.app.babyorder.vo.*;
import cn.iocoder.yudao.module.alipay.dal.dataobject.babyorder.BabyOrderDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.alipay.convert.babyorder.BabyOrderConvert;
import cn.iocoder.yudao.module.alipay.dal.mysql.babyorder.BabyOrderMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.alipay.enums.ErrorCodeConstants.*;

/**
 * 宝宝起名订单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class BabyOrderServiceImpl implements BabyOrderService {

    @Resource
    private BabyOrderMapper babyOrderMapper;

    @Resource
    private InfoAuthAliAppMapper infoAuthAliAppMapper;

    @Resource
    private PayRecordMapper payRecordMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public Long createBabyOrder(BabyOrderCreateReqVO createReqVO) {
        log.info("查询参数："+createReqVO);
        // 插入
        BabyOrderDO babyOrder = BabyOrderConvert.INSTANCE.convert(createReqVO);
        //validateBabyOrderExistsByBuyerId(babyOrder.getBuyerId());
        DateTime dateTime = new DateTime(babyOrder.getSolarDate());
        ChineseDate date = new ChineseDate(dateTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String outTradeNo = "QM"+ simpleDateFormat.format(new Date())+new Random().nextInt(10);;
        babyOrder.setOutTradeNo(outTradeNo);
        babyOrder.setLunarDate(date.toString());
        babyOrder.setCostPrise(BigDecimal.valueOf(88.88));
        babyOrder.setRetailPrise(BigDecimal.valueOf(9.9));
        babyOrder.setOrderStatues("3");
        babyOrder.setOrderTime(LocalDateTime.now());
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectByAppId(createReqVO.getAppId());
        babyOrder.setCreator(infoAuthAliAppDO.getCreator());
        babyOrderMapper.insert(babyOrder);
        // 返回
        return babyOrder.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBabyOrder(BabyOrderUpdateReqVO updateReqVO) {
        // 校验存在
        validateBabyOrderExists(updateReqVO.getId());
        BabyOrderDO babyOrderDO = babyOrderMapper.selectById(updateReqVO.getId());
        // 更新
        BabyOrderDO updateObj = BabyOrderConvert.INSTANCE.convert(updateReqVO);
        log.info("-------------------updateObj.getOrderStatues():"+updateObj.getOrderStatues());
        log.info("-------------------babyOrderDO:"+babyOrderDO);
        //支付成功則在支付记录表中生成记录
        if(updateObj.getOrderStatues().equals("1")){
            PayRecordDO payRecordDO = new PayRecordDO();
            payRecordDO.setOrderId(updateObj.getId());
            payRecordDO.setPayTime(LocalDateTime.now());
            payRecordDO.setRecordType("input");
            payRecordDO.setOutTradeNo(updateObj.getOutTradeNo());
            payRecordDO.setTradeNo(updateObj.getTradeNo());
            payRecordDO.setTotalAmount(babyOrderDO.getRetailPrise());
            payRecordDO.setBuyerId(updateObj.getBuyerId());
            payRecordDO.setAppId(updateObj.getAppId());
            payRecordDO.setCreator(babyOrderDO.getCreator());
            payRecordDO.setRemark(babyOrderDO.getRemark());
            payRecordMapper.insert(payRecordDO);
            AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(babyOrderDO.getCreator()));
            user.setTotalAmount(user.getTotalAmount().add(babyOrderDO.getRetailPrise()));
            adminUserApi.updateUserByDto(user);

        }
        babyOrderMapper.updateById(updateObj);
    }

    @Override
    public void deleteBabyOrder(Long id) {
        // 校验存在
        validateBabyOrderExists(id);
        // 删除
        babyOrderMapper.deleteById(id);
    }

    /*private void validateBabyOrderExistsByBuyerId(String buyerId) {
        if (babyOrderMapper.selectByBuyerId(buyerId) != null) {
            throw exception(BABY_ORDER_EXISTS);
        }
    }*/

    private void validateBabyOrderExists(Long id) {
        if (babyOrderMapper.selectById(id) == null) {
            throw exception(BABY_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public List<BabyOrderDO> getBabyBuyerId(String buyerId) {
        return babyOrderMapper.selectByBuyerId(buyerId);
    }

    @Override
    public List<BabyOrderDO> getBabyOrderList(Collection<Long> ids) {
        return babyOrderMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BabyOrderRespVO> getBabyOrderPage(BabyOrderPageReqVO pageReqVO) {
        PageResult<BabyOrderRespVO> babyOrderRespVOPageResult = BabyOrderConvert.INSTANCE.convertPage(babyOrderMapper.selectPage(pageReqVO));
        List<BabyOrderRespVO> list = babyOrderRespVOPageResult.getList();
        list.forEach(babyOrderRespVO -> {
            String appId = babyOrderRespVO.getAppId();
            InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(appId);
            if(infoAuthAliAppDO!=null){
                babyOrderRespVO.setAppName(infoAuthAliAppDO.getAppName());
            }
        });
        babyOrderRespVOPageResult.setList(list);
        return babyOrderRespVOPageResult;
    }

    @Override
    public List<BabyOrderDO> getBabyOrderList(BabyOrderExportReqVO exportReqVO) {
        return babyOrderMapper.selectList(exportReqVO);
    }

    @Override
    public Object getBabyOrderListByBuyerId(String buyerId) {
        Map<String,Object> resultMap = new HashMap<>();
        List<BabyOrderDO> babyOrderDO = babyOrderMapper.selectByBuyerId(buyerId);
        List<BabyOrderDO> babyOrderMapperInvalidBabyOrderListByBuyerId = babyOrderMapper.getInvalidBabyOrderListByBuyerId(buyerId);
        List<BabyOrderDO> babyOrderListByBuyerId = babyOrderMapper.getBabyOrderListByBuyerId(buyerId);
        List<BabyOrderDO> successBabyOrderListByBuyerId = babyOrderMapper.getSuccessBabyOrderListByBuyerId(buyerId);
        resultMap.put("pendingOrders",babyOrderDO);
        resultMap.put("loseEfficacyOrders",babyOrderListByBuyerId);
        resultMap.put("invalidOrders",babyOrderMapperInvalidBabyOrderListByBuyerId);
        resultMap.put("paidOrders",successBabyOrderListByBuyerId);
        return resultMap;
    }

    @Override
    public BabyOrderDO getBabyOrder(String id) {
        return babyOrderMapper.selectById(id);
    }

}
